<template>
  <div class="classroom-study">
    <div class="classroom-video" v-infinite-scroll="load" :infinite-scroll-disabled="disabled"
         :infinite-scroll-immediate="true">
      <h3>{{ pageTitle}}</h3>
      <div class="classroom-video-content">
        <!-- 视频信息区 -->
        <div class="video-title">{{info.videoName}}</div>
        <div class="video-info">
          <i class="classroom-book-icon"></i><span v-if="detail.subject">{{detail.subject}} · {{detail.grade}} · {{detail.volume}} · {{detail.version}}</span>
        </div>
        <div class="video-info video-info-teacher">
          <i class="classroom-teacher-icon"></i><span>授课教师：{{ info.createUserName }}</span>
          <!-- <i class="classroom-teacher-icon"></i><span>指导教师：杜锦芝</span> -->
          <i class="classroom-comment-icon"></i><span class="comment">{{info.leaveWordNum}}</span>
          <span class="collect-wrap" :class="{'is-active': collectActive}" @click="setCollection">
            <i class="classroom-collect-icon"></i><span class="collect">收藏</span>
          </span>
        </div>
        <!-- <div class="video-info">
          <i class="classroom-site-icon"></i><span>教育部资源中心</span>
          <i class="classroom-comment-icon"></i><span class="comment">{{info.leaveWordNum}}</span>
          <span class="collect-wrap" :class="{'is-active': collectActive}" @click="setCollection">
            <i class="classroom-collect-icon"></i><span class="collect">收藏</span>
          </span>
        </div> -->
        <!-- /视频信息区 -->

        <!-- 视频播放区 -->
        <div class="video-wrap">
          <div class="video-box" @contextmenu.prevent="false">
            <video-player class="video-player vjs-custom-skin" style="width: 100%;" ref="videoPlayer"
                          :playsline="false" :options="playerOptions" id="myvideo"
                          @play="playFun" @ended="endedFun" @pause="pauseFun"
                          controlslist="nodownload"></video-player>
          </div>
          <div class="video-box-right">
            <el-tabs :tab-position="'right'" v-model="tabActive" @tab-click="tabClick">
              <el-tab-pane name="1" disabled label="课时资源">
                <template slot="label">
                  <i class="classrooom-playlist-icon"></i>课时资源
                </template>
              </el-tab-pane>
              <el-tab-pane :label="item.videoName" :name="item.id" v-for="item in videoList"
                           :key="item.id">
                <template slot="label" v-if="isPlay(item.id)">
                  <span class="video-item-wrap is-active">
                    <i class="classrooom-play-icon"></i>{{item.videoName}}
                    <span class="label-icon"><i class="el-icon-s-data"></i><i class="el-icon-more"></i></span>
                  </span>
                  <!-- <span class="label-icon"><i class="icon-playing"></i><i class="el-icon-more"></i></span> -->
                </template>
                <template slot="label" v-else>
                  <span class="video-item-wrap">
                    <i class="classrooom-play-icon"></i>{{item.videoName}}
                    <!-- <span class="label-icon"><i class="el-icon-s-data"></i><i class="el-icon-more"></i></span> -->
                  </span>
                </template>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <!-- /视频播放区 -->

        <!-- 评论区 -->
        <div class="classroom-comment">
          <div class="classroom-comment-title">
            <label>评论</label><span>{{ total }}</span>
            <el-radio-group v-model="filterParams.orderBy" @change="refresh">
              <el-radio-button label="createTime">最新</el-radio-button>
              <el-radio-button label="likeNum">最热</el-radio-button>
            </el-radio-group>
          </div>
          <div class="classroom-comment-input">
            <el-avatar :size="42" :src="headPortraits">
              <img src="../assets/img/default-avatar.png" />
            </el-avatar>
            <div class="classroom-comment-content">
              <el-input v-model.trim="form.info" maxlength="200" placeholder="与其赞同别人的话语，不如自己畅所欲言。"
                        type="textarea" :autosize="{ minRows: 1, maxRows: 3}"></el-input>
              <el-button type="primary" @click="sendComment" :loading="sendLoading">发布</el-button>
            </div>
          </div>
          <List ref="list" :videoId="this.form.videoId"  @moreCallback="moreCallback"
                @refresh="getList" />
          <p v-if="moreLoading">加载中...</p>
          <p v-else-if="noMore">没有更多了</p>
          <p v-else></p>
        </div>
        <!-- /评论区域 -->
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import List from '../components/commentList'
// eslint-disable-next-line import/no-cycle
import { cloud } from '@/framework/utils/request'
import { add, getPage, addCollection, delCollection, qryVideoCollect, addHistory } from '@/api/onlineClass/comment'
import { getDetail } from '@/api/classroom/learnVideoManage'
import { zeroFill } from '@/utils/index.js'

// 引入样式
import 'video.js/dist/video-js.css'
import 'vue-video-player/src/custom-theme.css'

export default {
  name: 'ClassroomVideo',
  components: { List },
  data() {
    return {
      tabActive: '',
      collectActive: false, // 是否收藏
      videoList: [],
      total: 0,
      nowLength: 0,
      moreLoading: false,
      form: {
        info: '',
        videoId: ''
      },
      sendLoading: false,
      filterParams: {
        orderBy: 'createTime',
        pageNo: 1,
        pageSize: 10
      },
      loading: false,
      pageTitle: '',
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如'16:9'或'4:3'）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: 'video/mp4', // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
          src: 'https://api.dogecloud.com/player/get.mp4?vcode=5ac682e6f8231991&userId=17&ext=.mp4' // url地址
        }],
        // poster: '../../../../static/full_res.jpg', // 你的封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true, // 全屏按钮
          playToggle: true
        }
      },
      info: {},
      playTimeLength: 0,
      startTime: 0,
      endTime: 0,
      isPlaying: false // 判断是否在播放视频
    }
  },
  computed: {
    noMore() {
      return this.nowLength >= this.total
    },
    disabled() {
      return this.moreLoading || this.noMore
    },
    headPortraits() {
      return this.$store.state.user.avatar
    },
    ...mapGetters(['onlineStudy', 'studentInfo']),
    detail() {
      const subjectObj = this.dict.type.subject.find((n) => n.value == this.info.subject)
      const subject = subjectObj && subjectObj.label
      const gradeObj = this.dict.type.grade.find((n) => n.value == this.info.grade)
      const grade = gradeObj && gradeObj.label
      const versionObj = this.dict.type.version.find((n) => n.value == this.info.version)
      const version = versionObj && versionObj.label
      const volumeObj = this.dict.type.volume.find((n) => n.value == this.info.volume)
      const volume = volumeObj && volumeObj.label
      return {
        subject,
        grade,
        version,
        volume
      }
    }
  },
  watch: {
    studentInfo: {
      deep: true,
      handler() {
        this.getIsCollect()
      }
    }
  },
  dicts: ['grade', 'subject', 'version', 'volume'],
  mounted() {
    this.init()
    this.getVideoList() // 获取视频右侧 课程列表
  },
  beforeDestroy() {
    if (this.isPlaying) {
      this.endedFun()
    }
  },
  methods: {
    playFun() { // 记录播放开始时间的时间戳
      this.startTime = Math.floor(new Date().getTime() / 1000)
      this.isPlaying = true
    },
    pauseFun() {
      this.endTime = Math.floor(new Date().getTime() / 1000)
      this.playTimeLength = (this.endTime - this.startTime) + this.playTimeLength
      this.isPlaying = false
    },
    endedFun() {
      this.endTime = Math.floor(new Date().getTime() / 1000)
      this.playTimeLength = (this.endTime - this.startTime) + this.playTimeLength
      this.isPlaying = false
      if (this.studentInfo.id) {
        addHistory({
          studentId: this.studentInfo.id,
          videoId: this.form.videoId,
          playTime: this.playTimeLength
        })
      }
    },
    init() {
      this.form.videoId = this.$route.query.vid || '' // 这个id只是调试用, 联调完播放页面去掉
      this.filterParams.videoId = this.$route.query.vid || ''
      const routeObj = this.onlineStudy.find((item) => item.path == this.$route.query.menuPath)
      this.pageTitle = routeObj && routeObj.menuName
      this.getVideoInfo(this.form.videoId) // 获取课程信息
      this.getList() // 获取评论列表
      this.getIsCollect()// 查询视频是否被收藏
    },
    initData() {
      this.total = 0
      this.nowLength = 0
      this.moreLoading = false
      this.collectActive = false
      this.filterParams = {
        orderBy: 'createTime',
        pageNo: 1,
        pageSize: 10
      }
    },
    tabClick(val) {
      this.$router.push({
        path: '/onlineClassroom/study',
        query: {
          menuPath: this.$route.query.menuPath,
          vid: val.name
        }
      })
      this.$nextTick(() => {
        this.initData()
        this.init()
        this.$forceUpdate()
      })
    },
    getVideoList() {
      const list = JSON.parse(localStorage.getItem('courseDataList'))
      this.videoList = list
      this.tabActive = this.form.videoId
    },
    setCollection() { // 收藏
      if (!this.studentInfo.id) {
        this.$alert('您还没有学生，无法添加收藏，快去添加学生吧', '提示', {
          confirmButtonText: '去添加',
          showClose: false,
          callback: () => {
            this.$router.push({
              path: '/onlineClassroom/studentInfo'
            })
          }
        })
        return
      }
      if (this.collectActive) {
        this.collectActive = false
        delCollection({
          studentId: this.studentInfo.id,
          videoId: this.form.videoId
        })
        return
      }
      this.collectActive = true
      addCollection({
        studentId: this.studentInfo.id,
        videoId: this.form.videoId
      })
    },
    getIsCollect() { // 查询该视频是否被收藏
      if (this.studentInfo.id) {
        qryVideoCollect({
          studentId: this.studentInfo.id,
          videoId: this.form.videoId
        }).then((res) => {
          this.collectActive = res.data
        })
      }
    },
    getVideoInfo(id) {
      getDetail(id).then((res) => {
        this.info = res.data
      })
    },
    replayCallback(id) {
      this.refresh()
    },
    moreCallback(nowLength) {
      this.nowLength = nowLength
    },
    load() {
      if (!this.noMore && !this.moreLoading) {
        this.filterParams.pageNo++
        this.moreLoading = true
        this.getList('more')
      }
    },
    isPlay(i) {
      return i == this.tabActive
    },
    refresh() {
      this.filterParams.pageNo = 1
      this.getList()
      this.$refs.list.getMyLikeCommentId()
    },
    sendComment() {
      if (this.form.info) {
        this.sendLoading = true
        add(this.form).then((res) => {
          this.refresh()
        }).finally(() => {
          this.sendLoading = false
          this.form.info = ''
        })
      } else {
        this.$message.warning('不能发送空内容!')
      }
    },
    formatDate(dateStr) {
      if (!isNaN(Date.parse(dateStr))) {
        const dates = new Date(dateStr)
        const yyyy = dates.getFullYear()
        const MM = zeroFill(dates.getMonth() + 1)
        const dd = zeroFill(dates.getDate())
        const HH = zeroFill(dates.getHours())
        const mm = zeroFill(dates.getMinutes())
        return `${yyyy}-${MM}-${dd} ${HH}:${mm}`
      }
      return ''
    },
    getList(type) { // 获取评论列表
      this.loading = true
      getPage(this.filterParams).then((res) => {
        this.total = res.data.totalRows
        const arr = res.data.rows.map((item) => {
          item.createTime = this.formatDate(item.createTime)
          item.avatarUrl = `${location.origin}${process.env.VUE_APP_BASE_API}${cloud.file}/sysFileInfo/public/preview?fileId=${item.createUserAvatar}`
          item.likeNum = item.likeNum > 0 ? item.likeNum : 0
          item.children = []
          return item
        })
        if (type == 'more') {
          this.$refs.list.more(arr)
        } else {
          this.$refs.list.getData(arr)
        }
      }).catch(() => {
        this.nowLength = 0
      }).finally(() => {
        this.loading = false
        this.moreLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.classroom-study {
  height: calc(100vh - 80px);
  // height: 100%;
  overflow: auto;
  box-sizing: border-box;
  padding: 20px;
}
.classroom-video {
  width: 100%;
  h3 {
    font-family: "Source Han Sans CN Medium";
    font-weight: 600;
    font-size: 24px;
    text-align: left;
    color: #00080f;
    margin-block-start: 0;
    margin-block-end: 0;
    margin-bottom: 20px;
  }
  &-content {
    width: 100%;
    border-radius: 4px;
    background: #fff;
    box-shadow: 0 3px 6px #00000029;
    padding: 20px;
    .video-title {
      font-family: "Source Han Sans CN";
      font-weight: 500;
      font-size: 20px;
      text-align: left;
      color: #00080f;
      margin-bottom: 22px;
    }
    .video-info {
      font-family: "Source Han Sans CN";
      font-weight: 400;
      font-size: 14px;
      text-align: left;
      color: #808080;
      margin-bottom: 22px;
      span {
        margin-right: 38px;
        vertical-align: middle;
      }
      i {
        display: inline-block;
        width: 14px;
        height: 14px;
        vertical-align: middle;
        margin-right: 2px;
      }
      .collect-wrap {
        cursor: pointer;
      }
      .is-active {
        .collect {
          color: #ff7b3f;
        }
        .classroom-collect-icon {
          background: url("../assets/icons/collect-active-icon.png") no-repeat;
          background-size: cover;
        }
      }
      .comment {
        color: #004fff;
      }
    }
    .video-info-teacher {
      span {
        margin-right: 22px;
      }
    }
    .video-wrap {
      display: flex;
      width: 100%;
      .video-box {
        width: 80.88%;
      }
      .video-box-right {
        width: 19%;
        .label-icon {
          position: absolute;
          right: 12px;
          i {
            margin-left: 2px;
          }
          .icon-playing {
            display: inline-block;
            width: 16px;
            height: 16px;
            background: url('../assets/icons/icon-playing.gif');
            background-size: cover;
            // margin-right: 10px
          }
        }
        .classrooom-playlist-icon {
          display: inline-block;
          width: 14px;
          height: 14px;
          background: url("../assets/icons/playlist-icon.png") no-repeat;
          background-size: cover;
          margin-right: 2px;
        }
        .video-item-wrap {
          display: inline-block;
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          i {
            display: inline-block;
            width: 14px;
            height: 14px;
            vertical-align: middle;
            margin-right: 2px;
          }
          span {
            vertical-align: middle;
          }
        }
        .is-active {
          width: 80%;
          .classrooom-play-icon {
              background: url("../assets/icons/play-active-icon.png") no-repeat;
              background-size: cover;
          }
        }
      }
    }
  }
}
.classroom-comment {
  font-family: "Source Han Sans CN";
  padding-top: 40px;
  &-title {
    font-weight: 400;
    font-size: 20px;
    color: #00080f;
    margin-bottom: 20px;
    span {
      font-weight: 400;
      font-size: 14px;
      color: #808080;
      margin-left: 6px;
      margin-right: 16px;
    }
  }
  &-input {
    position: relative;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .el-avatar {
      width: 42px;
      margin-right: 12px;
      flex: none;
    }
    .el-textarea {
      width: 83%;
      ::v-deep textarea {
        background: #f1f2f3;
        min-height: 43px !important;
      }
    }
    ::v-deep .el-textarea__inner:focus {
      border-color: #f1f2f3;
    }
  }
  &-content {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  > p {
    text-align: center;
    font-size: 14px;
  }
}
.classroom-book-icon {
  background: url("../assets/icons/book-icon.png") no-repeat;
  background-size: cover;
}
.classroom-teacher-icon {
  background: url("../assets/icons/teacher-icon.png") no-repeat;
  background-size: cover;
}
.classroom-site-icon {
  background: url("../assets/icons/site-icon.png") no-repeat;
  background-size: cover;
}
.classroom-comment-icon {
  background: url("../assets/icons/comment-icon.png") no-repeat;
  background-size: cover;
}
.classroom-collect-icon {
  background: url("../assets/icons/collect-icon.png") no-repeat;
  background-size: cover;
}
.classrooom-play-icon {
  background: url("../assets/icons/play-icon.png") no-repeat;
  background-size: cover;
}
</style>

<style lang="scss">
// .classroom-video {
//   .video-js .vjs-play-progress:before {
//     line-height: 1;
//   }
//   .video-js .vjs-volume-panel.vjs-volume-panel-horizontal:hover,
//   .video-js .vjs-volume-panel.vjs-volume-panel-horizontal:active,
//   .video-js .vjs-volume-panel.vjs-volume-panel-horizontal.vjs-slider-active {
//       width: 9em;
//       -webkit-transition: width 0.1s;
//       transition: width 0.1s;
//   }
// }
.classroom-video .video-box-right {
  .el-tabs--right .el-tabs__header.is-right{
    float: none !important;
    margin-left: 2px;
  }
  .el-tabs__item {
    width: 100%;
    font-family: "Source Han Sans CN";
    font-weight: 400;
    font-size: 16px;
    text-align: left;
    color: #808080;
    height: 42px;
  }
  .el-tabs__item.is-active, .el-tabs__item:hover {
    color: #004fff;
    background: #edf2fc;
  }
  .el-tabs__item.is-disabled, .el-tabs__item.is-disabled:hover {
    color: #004fff !important;
    font-weight: 600 !important;
    // font-size: 16px !important;
    background: transparent;
  }
  .el-tabs--right .el-tabs__active-bar.is-right {
    left: auto;
    right: 0;
  }
  .el-tabs__active-bar {
    background: #004FFF;
    border-radius: 1px;
  }
}
.classroom-comment {
  .el-input__inner:focus {
    border-color: #dcdfe6;
  }
  .el-radio-button__inner {
    border: none;
    font-weight: 500;
    font-size: 14px;
    color: #808080;
    padding: 0 6px;
  }
  .el-radio-button:first-child .el-radio-button__inner {
    border-left: none;
    border-right: 2px solid #000 !important;
  }
  .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    background-color: transparent;
    color: #000;
  }
}
</style>
